import os
import requests
from machine import Pin
import time
import _thread
from oledprint import getI2Cstatue,threaded_print,OLEDPrinter
from wavplayer import  playwav,playwavfile
w=getI2Cstatue()
if w :
    oled_printer = OLEDPrinter(w)  
    global print  # 声明 print 为全局变量
    def print(*args, **kwargs):
        threaded_print(oled_printer,*args, **kwargs)
class FileUploader:
    CHUNK_SIZE = 2 * 1024
    BOUNDARY = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
    def __init__(self):
        self.led = Pin(2, Pin.OUT)
        self.led.value(0)
        self.led_thread_running = False
    def _led_blink_thread(self):
        """
        LED 闪烁线程
        """
        while self.led_thread_running:
            self.led.value(1)
            time.sleep_ms(200)
            self.led.value(0)
            time.sleep_ms(200)

    def start_led_thread(self):
        """
        启动 LED 闪烁线程
        """
        if not self.led_thread_running:
            self.led_thread_running = True
            _thread.start_new_thread(self._led_blink_thread, ())

    def stop_led_thread(self):
        """
        停止 LED 闪烁线程
        """
        self.led_thread_running = False
        time.sleep_ms(200)
    @staticmethod
    def create_multipart_body(randomname, file_chunk, is_last):
        """
             构建 multipart/form-data 请求体
             :param randomname: 随机生成的文件名
             :param file_chunk: 文件数据块
             :param is_last: 是否是最后一个数据块
             :return: bytes 请求体
             """
        body = [
            f'--{FileUploader.BOUNDARY}'.encode('utf-8'),
            b'Content-Disposition: form-data; name="file_name"',
            b'',
            randomname.encode('utf-8'),
            f'--{FileUploader.BOUNDARY}'.encode('utf-8'),
            f'Content-Disposition: form-data; name="file_chunk"; filename="{randomname}"'.encode('utf-8'),
            b'Content-Type: application/octet-stream',
            b'',
            file_chunk,
            f'--{FileUploader.BOUNDARY}'.encode('utf-8'),
            b'Content-Disposition: form-data; name="is_last"',
            b'',
            str(is_last).encode('utf-8'),
            f'--{FileUploader.BOUNDARY}--'.encode('utf-8'),
            b''
        ]
        return b'\r\n'.join(body)

    def upload_file(self, file_path, randomname, upload_url):
        """
               上传文件
               :param file_path: 文件路径
               :param randomname: 随机生成的文件名
               :param upload_url: 上传的 URL
             """
        try:
            self.start_led_thread()
            with open(file_path, 'rb') as f:
                file_size = os.stat(file_path)[6]
                num_chunks = (file_size // self.CHUNK_SIZE) + (1 if file_size % self.CHUNK_SIZE else 0)
                print(f"文件大小: {file_size} 块数: {num_chunks}")
                for i in range(num_chunks):
                    print(f"第 {i+1} 个数据块上传开始")
                    chunk = f.read(self.CHUNK_SIZE)

                    is_last_chunk = 1 if i == num_chunks - 1 else 0
                    body = self.create_multipart_body(randomname, chunk, is_last_chunk)
    
                    headers = {
                        'Content-Type': f'multipart/form-data; boundary={self.BOUNDARY}',
                        'Content-Length': str(len(body))
                    }
                    response = requests.post(upload_url, data=body, headers=headers,timeout=30,)
                    if response.status_code == 204:
                        print(f"第 {i+1} 个数据块上传成功")
                    if response.status_code == 200:
                        self.stop_led_thread()
                        time.sleep_ms(200)
                        self.led.value(0)
                        playwav(response)
                        return
                    if response.status_code not in (200, 204):
                        raise Exception(__file__+"上传失败, 状态码: "+str(response.status_code))
        except Exception as e:
            print(e)
            self.stop_led_thread()
            time.sleep_ms(200)
            self.led.value(0)
            playwavfile("error.wav")
            
if __name__=="__main__":
    t=FileUploader()
    t.upload_file("audio.wav", "ee.wav", "http://192.168.1.15:8052")